#define  _CRT_SECURE_NO_WARNINGS
#include"list.h"

list* listinit()
{
	list*phead = (list*)malloc(sizeof(list));
	phead->next = phead;
	phead->pre = phead;
	return phead;
}

void listpushback(list* phead, datatype x)
{
	assert(phead);
	//list* tail = phead->pre;
	//list* p = (list*)malloc(sizeof(list));
	//p->data = x;
	//tail->next = p;
	//p->pre = tail;
	//p->next = phead;
	//phead->pre = p;
	listinsert(phead, x);
}

void listprint(list* phead)
{
	assert(phead);
	list* p = phead->next;
	while (p != phead)
	{
		printf("%d ", p->data);
		p = p->next;
	}
	printf("\n");
}

void listpushfront(list* phead, datatype x)
{
	assert(phead != NULL);
	//list* p = (list*)malloc(sizeof(list));
	//list* next = phead->next;
	//p->data = x;
	//p->next = next;
	//phead->next = p;
	//p->pre = phead;
	//next->pre = p;
	listinsert(phead->next, x);
}

void listfreeback(list* phead)
{
	assert(phead->next != phead&&phead!=NULL);
	//list* tail = phead->pre;
	//list* p = tail->pre;
	//p->next = phead;
	//phead->pre = p;
	//free(tail);
	listfree2(phead->pre);
}


void listfreefront(list* phead)
{
	assert(phead->next != phead && phead != NULL);
	//list* p = phead->next;
	//phead->next = p->next;
	//p->next->pre = phead;
	//free(p);
	listfree2(phead->next);
}

list* listfindpos(list* phead, int y)
{
	assert(phead);
	list* p = phead->next;
	while (p!=phead)
	{
		if (p->data == y)
		{
			return p;
		}
		p = p->next;
	}	
}

void listinsert(list* pos, datatype x)
{
	assert(pos);
	list* p = (list*)malloc(sizeof(list));
	p->data = x;
	list* pre = pos->pre;
	pre->next = p;
	p->pre = pre;
	p->next = pos;
	pos->pre = p;
}

void listfree1(list* pos)
{
	assert(pos);
	list* p = pos->pre;
	p->pre->next = pos;
	pos->pre = p->pre;
	free(p);
}

void listfree2(list* pos)
{
	assert(pos);
	list* p = pos->pre;
	p->next = pos->next;
	pos->next->pre = p;
	free(pos);
}

void listdestory(list** phead)
{
	assert(*phead);
	list* p = (*phead)->next;
	while (p!=*phead)
	{
		list*next = p->next;
		free(p);
		p = next;
		
	}
	free(*phead);
	*phead = NULL;


}